/*
 * Copyright 2019-2029 geekidea(https://github.com/geekidea)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.zwcl.common.web.filter;

import com.zwcl.common.core.constant.CacheConstants;
import com.zwcl.common.core.domain.entity.CacheUser;
import com.zwcl.common.core.utils.IpUtils;
import com.zwcl.common.core.utils.StringUtilsEx;
import com.zwcl.common.web.domain.RequestDetail;
import com.zwcl.common.web.utils.GetLoginUserService;
import com.zwcl.common.web.utils.RequestDetailContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.server.reactive.ServerHttpRequest;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 请求详情信息Filter
 *
 * @author geekidea
 * @date 2020/3/25
 **/
@Slf4j
@Configuration
public class RequestDetailFilter implements Filter {

    @Autowired
    private GetLoginUserService getLoginUserService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("RequestDetailFilter init");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 设置请求详情信息
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        // 请求IP
        String ip = IpUtils.getIpAddr(httpServletRequest);
        // 请求路径
        String path = httpServletRequest.getRequestURI();
        String traceId = httpServletRequest.getHeader(CacheConstants.REQUEST_TRACE);
        RequestDetail requestDetail = new RequestDetail()
                .setIp(ip)
                .setPath(path)
                .setTraceId(traceId);
        String userId = httpServletRequest.getHeader(CacheConstants.DETAILS_USER_ID);
        String userName = httpServletRequest.getHeader(CacheConstants.DETAILS_USERNAME);
        if(StringUtils.isBlank(userId)) {
            //有的话，获取用户的token，从而拿到用户信息
            CacheUser loginUser = getLoginUserService.getUserFromHead(httpServletRequest);
            if (loginUser != null) {
                requestDetail.setUserId(loginUser.getUserId().toString()).setUserName(loginUser.getUserName());
            }
        }else {
            requestDetail.setUserId(userId).setUserName(userName);
        }
        // 设置请求详情信息
        RequestDetailContext.setRequestDetail(requestDetail);
        chain.doFilter(request, response);
        // 释放
        RequestDetailContext.remove();
    }

    @Override
    public void destroy() {
        log.info("RequestDetailFilter destroy");
    }

}
